# 白雪需要的数据处理
# 查询同一个病人，48小时内又入院的，原始文件包含 病案号，入院时间，出院时间 三元组
import codecs
import os
import datetime
from logging import ERROR
import pymssql
limit = 48
exceptdata = []
server = "10.160.12.192"
u = "sa"
password = "Docimax@123"

DbMrfs = "MR_FS_DB"
sql = '''
select mrid,AdmissionDateTime,DischargeDateTime from vbase where
 DischargeDateTime between '2018-1-1' and '2019-11-1'  
    and (OutDepartCode not like '国际%')   
	and (OutSickRoomCode not like '国际%') 
    and PaymentTypeCode not in ('6','7','9')
    order by mrid,AdmissionDateTime
    '''
conn = pymssql.connect(server, u, password, DbMrfs)  # 获取连接
cursor = conn.cursor()  # 获取光标
cursor.execute(sql)

# 遍历数据（存放到元组中） 方式1
rows = cursor.fetchall()


def dbValid(data):
    returndata = []
    current = ''
    validdata = []
    i = 0.0
    t = len(data)
    print('t=')
    print(t)
    for d in data:
        i = i+1
        print(i/t)
        if(current != d[0]):
            if(dbvalid(validdata, current)):
                print('OK')
                returndata.append(current)
            current = d[0]
            validdata = []

        validdata.append((d[1], d[2]))
    return returndata


def dbvalid(data, mrid):
    if(len(data) < 2):
        #print('less len')
        return False

    for i in range(1, len(data)):
        # sts=data[i-1][1].replace('\n', '')
        # ets=data[i][0].replace('\n', '')
        # if(sts!=NULL)
        try:
            et = data[i][0]
            st = data[i-1][1]

            dt = et-st
            print(dt)
            if(dt > datetime.timedelta(hours=0) and dt < datetime.timedelta(hours=limit)):
                return True
        except Exception as e:
            print('ERROR:', e)
            print(ERROR)
            print(mrid)
            exceptdata.append(mrid)

    return False


def showData(data):
    for d in data:
        print(d)


def readData(path):
    data = []
    with open(path, 'r') as f:
        data = f.readlines()

    return data


def valid(data, mrid):
    if(len(data) < 2):
        #print('less len')
        return False

    for i in range(1, len(data)):
        # sts=data[i-1][1].replace('\n', '')
        # ets=data[i][0].replace('\n', '')
        # if(sts!=NULL)
        try:
            et = datetime.datetime.strptime(
                data[i][0].replace('\n', ''), "%Y/%m/%d %H:%M")
            st = datetime.datetime.strptime(
                data[i-1][1].replace('\n', ''), "%Y/%m/%d %H:%M")

            dt = et-st
            print(dt)
            if(dt > datetime.timedelta(hours=0) and dt < datetime.timedelta(hours=limit)):
                return True
        except Exception as e:
            print('ERROR:', e)
            print(ERROR)
            print(mrid)
            exceptdata.append(mrid)

    return False


def allValid(data):
    returndata = []
    current = ''
    validdata = []
    i = 0.0
    t = len(data)
    print('t=')
    print(t)
    for d in data:
        i = i+1
        print(i/t)
        r = d.split(',')
        if(current != r[0]):

            if(valid(validdata, current)):
                print('OK')
                returndata.append(current)
            current = r[0]
            validdata = []

        validdata.append((r[1], r[2]))
    return returndata


def exportCsv(result, name):
    fout = open(name, 'w')
    s = ''
    for c in (result):
        s = s+c+','

    fout.write(s)

    fout.close()


#d = readData('D:\\tmp\\mrid.csv')
rd = dbValid(rows)
print(rd)
exportCsv(rd, 'result.csv')
exportCsv(exceptdata, 'except.csv')
print(exceptdata)
